﻿using AspNetCore.HttpClientAndPolly.PollyAttribute;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Net;

namespace AspNetCore.HttpClientAndPolly.PollyHelper
{
    /// <summary>
    /// 模拟Http请求
    /// </summary>
    public class RequestApi
    {
        /// <summary>
        /// Get
        /// </summary>
        [CustomPollyRetry(Order = 2)]
        [CustomPollyTimeOut(Order = 1)]
        public virtual async Task<T> Get<T>(HttpClient httpClient, string url, object param = null)
        {
            T result = default(T);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            StringBuilder requestUri = new StringBuilder(url);
            var response = await httpClient.GetAsync(requestUri.ToString());
            var res = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                result = JsonConvert.DeserializeObject<T>(res);
            }
            else
            {
                throw new Exception(JsonConvert.SerializeObject(response.RequestMessage));
            }
            return result;
        }

        /// <summary>
        /// Post
        /// </summary>
        [CustomPollyRetry(Order = 2)]
        [CustomPollyTimeOut(Order = 1)]
        public virtual async Task<T> Post<T>(HttpClient httpClient, string url, object param)
        {
            T result = default(T);
            var content = JsonConvert.SerializeObject(param);
            HttpContent httpContent = new StringContent(content);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await httpClient.PostAsync(url, httpContent);
            var res = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                result = JsonConvert.DeserializeObject<T>(res);
            }
            else
            {
                throw new Exception(JsonConvert.SerializeObject(response.RequestMessage));
            }
            return result;
        }
    }
}
